package com.dxy.dxyuser.config;

import com.alibaba.fastjson.JSON;
import com.dxy.dxycommon.utils.CookieUtil;
import com.dxy.dxycommon.utils.ResultVOUtil;
import com.dxy.dxyuser.annotation.Authorization;
import com.dxy.dxyuser.constant.CookieConstant;
import com.dxy.dxyuser.constant.RedisConstant;
import com.dxy.dxyuser.enums.ResultEnum;
import com.dxy.dxyuser.service.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;

//登录拦截器
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.getAnnotation(Authorization.class) == null) {
            return true;
        }
        // 获取header中传的token和cookie中的userId
        String authorization = httpServletRequest.getHeader(RedisConstant.AUTHORIZATION).substring(6).trim();
        String userId;
        try {
            userId = CookieUtil.get(httpServletRequest, CookieConstant.USERID).getValue();
        } catch (Exception e) {
            userId = null;
        }
        //拦截后返回的信息
        String result = JSON.toJSONString(ResultVOUtil.error(ResultEnum.NOT_IDENTITY_USER));
        if (userId == null) {
            //1.拦截：cookie 中没有userId
            outStreamMsg(result, httpServletResponse);
            return false;
        } else {
            if (tokenManager.isExistToken(userId)) {
                httpServletRequest.setAttribute(CookieConstant.USERID, userId);
                //token一致，放行
                if (authorization.equals(stringRedisTemplate.opsForValue().get(userId))) {
                    return true;
                } else {
                    //2.拦截：token不一致
                    outStreamMsg(result, httpServletResponse);
                    return false;
                }
            } else {
                //3.拦截：token不存在
                outStreamMsg(result, httpServletResponse);
                return false;
            }
        }
    }


    /**
     * 以流的形式输出拦截信息
     *
     * @param result
     * @param httpServletResponse
     */
    public void outStreamMsg(String result, HttpServletResponse httpServletResponse) {
        PrintWriter writer = null;
        OutputStreamWriter osw;
        try {
            osw = new OutputStreamWriter(httpServletResponse.getOutputStream(), "UTF-8");
            writer = new PrintWriter(osw, true);
            writer.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }
    }


}
